<template>
  <van-popup
    v-model:show="show"
    position="bottom"
    round
    :style="{ height: '4.2rem' }"
  >
    <div class="cdkExchange">
      <div class="title">
        请输入兑换码
      </div>
      <van-field
        v-model="cdk"
        style="padding:0.05rem 0 0.07rem 0.22rem; background: rgba(172,172,172,0.20);border-radius: 0.08rem; margin-bottom: 0.3rem; font-size: 0.28rem;"
        clearable
        placeholder="请输入兑换码"
      />
      <div class="split"></div>
      <div :class="['exchangeBtn', {'exchangeDisabled': exchangeDisabled}]" @click="doExchange">
        兑换
      </div>
    </div>
  </van-popup>
</template>
<script>
import { getExchangeName } from '@/lib/js/utils/activity'
import $api from '../api'
import { Toast, Dialog  } from 'vant'
export default{
  props: {
    isShow:{
      type: Boolean,
      default:false
    },

    defaultRecords: {
      type: Array,
      default(){
        return []
      }
    }

  },
  emits:['update:isShow'],
  data(){
    return {
      show: false,
      cdk: ''
    }
  },

  computed: {
    exchangeDisabled(){
      return this.cdk.length <= 0
    }
  },

  watch: {
    isShow:{
      handler(value){
        this.show = value
      },
      immedate:true
    },

    show:{
      handler(value){
        this.$emit('update:isShow', value)
      },
      immedate:true
    }
  },

  methods: {
    async loadList(){

    },

    onRefresh(){

    },

    getExchangeName(item){
      const nextItem = {
        type: item.TargetType,
        count: item.TargetCount,
        name: item.Name
      }
      return getExchangeName(nextItem)
    },

    async doExchange(){
      if(this.cdk.length !== 16){
        Toast.fail('请输入正确的16位兑换码！')
        return
      }
      Toast.loading({
        message: '兑换中...'
      })
      try{
        const res = await $api.cdkExchange(this.cdk)
        Toast.clear()
        Dialog.alert({
          title: '兑换成功',
          message: `你已成功兑换 ${res.name}×${res.count}天，请前往奖励中心查看。`
        }).then(() => {
          // on close
        })
        this.show = false
        this.cdk = ''

      }catch(e){
        Toast.fail({
          message: '兑换码无效/已过期'
        })
        Toast.clear()
      }finally{

      }

    }
  }
}
</script>
<style lang="scss" scoped>
  .cdkExchange{
    padding: 0.46rem 0.3rem 0 0.3rem;

    .title{
      font-size: 0.32rem;
      color: #000;
      font-weight: 600;
      margin-bottom: 0.34rem;
    }

    .split{
      border-bottom: 1px solid rgba(172,172,172,0.20);
      margin-bottom: 0.3rem;
    }

    .exchangeBtn{
      height: 0.8rem;
      line-height: 0.8rem;
      background: #FFC811;
      border-radius: 0.16rem;
      color: #fff;
      font-size: 0.32rem;
      text-align: center;
    }
    .exchangeDisabled{
      opacity: 0.4;
    }
  }
</style>
